using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using Publicuse.Entity;
using Publicuse.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Publicuse.Util
{
    /// <summary>
    /// 本周工具类
    /// </summary>
    public class WeekUtil
    {
        /// <summary>
        /// 获取当前时间是星期几
        /// </summary>
        /// <returns></returns>
        public static string GetDayOfWeek()
        {
            string[] Day = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
            string week = Day[Convert.ToInt32(DateTime.Now.DayOfWeek.ToString("d"))].ToString();
            return week;
        }

        /// <summary>
        /// 得到本周第一天(以星期天为第一天)
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static DateTime GetWeekFirstDaySun(DateTime datetime)
        {
            //星期天为第一天
            int weeknow = Convert.ToInt32(datetime.DayOfWeek);
            int daydiff = (-1) * weeknow;

            //本周第一天
            string FirstDay = datetime.AddDays(daydiff).ToString("yyyy-MM-dd");
            return Convert.ToDateTime(FirstDay);
        }

        /// <summary>
        /// 得到本周第一天(以星期一为第一天)
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static DateTime GetWeekFirstDayMon(DateTime datetime)
        {
            //星期一为第一天
            int weeknow = Convert.ToInt32(datetime.DayOfWeek);

            //因为是以星期一为第一天，所以要判断weeknow等于0时，要向前推6天。
            weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
            int daydiff = (-1) * weeknow;

            //本周第一天
            string FirstDay = datetime.AddDays(daydiff).ToString("yyyy-MM-dd");
            return Convert.ToDateTime(FirstDay);
        }

        /// <summary>
        /// 得到本周最后一天(以星期六为最后一天)
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static DateTime GetWeekLastDaySat(DateTime datetime)
        {
            //星期六为最后一天
            int weeknow = Convert.ToInt32(datetime.DayOfWeek);
            int daydiff = (7 - weeknow) - 1;

            //本周最后一天
            string LastDay = datetime.AddDays(daydiff).ToString("yyyy-MM-dd");
            return Convert.ToDateTime(LastDay);
        }

        /// <summary>
        /// 得到本周最后一天(以星期天为最后一天)
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static DateTime GetWeekLastDaySun(DateTime datetime)
        {
            //星期天为最后一天
            int weeknow = Convert.ToInt32(datetime.DayOfWeek);
            weeknow = (weeknow == 0 ? 7 : weeknow);
            int daydiff = (7 - weeknow);

            //本周最后一天
            string LastDay = datetime.AddDays(daydiff).ToString("yyyy-MM-dd");
            return Convert.ToDateTime(LastDay);
        }

        /// <summary>
        /// 获取当前月所有周信息
        /// </summary>
        /// <param name="datetime"></param>
        /// <returns></returns>
        public static List<MonthWeek> GetMonthWeekList(DateTime datetime)
        {
            List<MonthWeek> monthWeeks = new List<MonthWeek>();
            //年
            int year = datetime.Year;
            //月
            int month = datetime.Month;
            //当前月第一天
            DateTime weekStart = new DateTime(year, month, 1);
            //该月的最后一天
            DateTime monEnd = weekStart.AddMonths(1).AddDays(-1);
            int i = 0;
            //当前月第一天是星期几
            int dayOfWeek = Convert.ToInt32(weekStart.DayOfWeek.ToString("d"));
            //该月第一周结束日期
            DateTime weekEnd = dayOfWeek == 0 ? weekStart : weekStart.AddDays(7 - dayOfWeek);
            List<string> weeklist = new List<string>();
            //当日期小于或等于该月的最后一天
            while (weekEnd < monEnd)
            {
                if (i > 0)
                {
                    //该周的开始时间
                    weekStart = weekEnd.AddDays(1);
                }
                //该周结束时间
                weekEnd = weekStart.AddDays(6);
                i++;
                MonthWeek monthWeek = new MonthWeek()
                {
                    year = year,
                    month = month,
                    weekindex = i,
                    weekStart = weekStart.ToString("yyyy-MM-dd"),
                    weekEnd = weekEnd.ToString("yyyy-MM-dd"),
                    remark = " 开始时间： " + weekStart.ToString("yyyy-MM-dd") + "   结束时间： " + weekEnd.ToString("yyyy-MM-dd")
                };
                monthWeeks.Add(monthWeek);
            }
            return monthWeeks;
        }

        /// <summary>
        /// 判断是不是周末/节假日；周末和节假日返回true，工作日返回false
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static bool IsHolidayByDate(DateTime date)
        {
            var isHoliday = false;
            var webClient = new System.Net.WebClient();
            var PostVars = new System.Collections.Specialized.NameValueCollection{{ "d", date.ToString("yyyyMMdd") }};
            try
            {
                var day = date.DayOfWeek;

                //判断是否为周末
                if (day == DayOfWeek.Sunday || day == DayOfWeek.Saturday)
                    return true;

                //0为工作日，1为周末，2为法定节假日
                var byteResult =  webClient.UploadValuesTaskAsync("http://tool.bitefu.net/jiari/", "POST", PostVars).GetAwaiter().GetResult();//请求地址,传参方式,参数集合
                var result = Encoding.UTF8.GetString(byteResult);//获取返回值
                if (result == "1" || result == "2")
                    isHoliday = true;
            }
            catch(Exception ex)
            {
                isHoliday = false;
            }
            return isHoliday;
        }

        /// <summary>
        /// 判断当天是否工作日
        /// </summary>
        /// <param name="day"></param>
        /// <param name="mySqlSugar"></param>
        /// <returns></returns>
        public static bool ISWookDay(DateTime day,IMySqlSugarService mySqlSugar)
        {
            var ispass = false;
            var table = TableAtributeUtil.GetTable<Holiday>();
            var year = day.ToString("yyyy");
            var sql = $"select * from {table} where hYear='{year}';";
            var list = mySqlSugar.Query<Holiday>(sql,null,out var msg);
            if(string.IsNullOrEmpty(msg) && list!=null && list.Count > 0)
            {
                var holidaylist = list.Where(o => o.hName != "工作日");
                var worklist = list.Where(o => o.hName == "工作日").Select(o=>o.Remark).FirstOrDefault().Split(',');
                var curday = day.ToString("yyyy-MM-dd");
                ispass = worklist.Any(o => o == curday);
                var isholiday = false;
                if (!ispass)
                {
                    foreach (var item in holidaylist)
                    {
                        var starttime = item.hsTime;
                        var endtime = item.heTime;
                        if (day > Convert.ToDateTime(starttime) && day < Convert.ToDateTime(endtime))
                        {
                            isholiday = true;
                            break;
                        }
                    }
                    if (!isholiday)
                    {
                        bool isWeekend = day.DayOfWeek.ToString() == "Sunday" || day.DayOfWeek.ToString() == "Saturday";
                        if (!isWeekend)
                        {
                            ispass = true;
                        }
                    }
                }
            }
            return ispass;
        } 
    }

    public class MonthWeek
    {
        public int weekindex { get; set; }

        public string weekStart { get; set; }

        public string weekEnd { get; set; }

        public int year { get; set; }

        public int month { get; set; }

        public string remark { get; set; }
    }
}
